//
//  NetworkHandler.m
//  LoveCar
//
//  Created by Xue Senhong on 15/5/21.
//  Copyright (c) 2015年 薛森鸿. All rights reserved.
//

#import "NetworkHandler.h"

@implementation NetworkHandler

- (void)getDataWithURLString:(NSString *)urlStr completion:(BLOCK)block
{
    // 1.先给自己的block属性赋值
    self.passValue = block;
    
    NSString *str = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:str];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.f];
    
    [request setHTTPMethod:@"GET"];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (nil != data) {
            
            id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            // block的使用 在获取到数据之后 使用
            // 将解析的结果传给 视图控制器
            self.passValue(object);
        }
    }];
    
}

+ (void)connectNetGETDataWithURLString:(NSString *)urlStr completion:(BLOCK)block
{
    NetworkHandler *network = [[NetworkHandler alloc] init];
    [network getDataWithURLString:urlStr completion:block];
    [network autorelease];
}

- (void)dealloc
{
    [super dealloc];
}

@end
